import axios from 'axios'
import mpAdapter from 'axios-miniprogram-adapter'
import { getAuthorization } from '../auth/index'
import { gethttpUrl } from './index'
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'
axios.defaults.adapter = mpAdapter as any
interface Result<T = any> {
  Code: number | string
  Data: T
  Msg: string
  MsgType: string
}

// 导出Request类，可以用来自定义传递配置来创建实例
class HttpRequest {
  baseURL: string
  timeout: number

  constructor() {
    this.baseURL = gethttpUrl()
    this.timeout = 60000
  }

  request<T = any>(options: AxiosRequestConfig): Promise<T> {
    // axios 实例
    const instance: AxiosInstance = axios.create()
    this.setInterceptors(instance)
    const opts = this.mergeOptions(options)
    return instance(opts)
  }

  get<T = any>(url: string, data?: any, outHeaders = {}): Promise<T> {
    return this.request<T>({
      method: 'get',
      url,
      params: { ...data }, // get参数可以直接展开
    })
  }

  post<T = any>(url: string, data = {}, outHeaders = {}): Promise<T> {
    return this.request<T>({
      method: 'post',
      url,
      data, // post要求必须传入data属性
    })
  }
  mergeOptions(options: AxiosRequestConfig) {
    //console.log('合并参数', options)
    return {
      baseURL: this.baseURL,
      timeout: this.timeout,
      headers: {
        ReqDeviceType: 'MobileApp', // app端登录要加的请求头
        Authorization: getAuthorization(),
      },
      ...options,
    }
  }
  // 设置拦截器
  setInterceptors(instance: AxiosInstance) {
    // 请求拦截器
    instance.interceptors.request.use(
      (config: any) => {
        // uni.showLoading({
        //   title: '加载中...',
        //   mask: true,
        // })
        return config
      },
      (err: any) => {
        console.log(err, '请求拦截报错')
        uni.hideLoading()
        return Promise.reject(err)
      }
    )

    // 响应拦截器
    instance.interceptors.response.use(
      (res: AxiosResponse) => {
        //res为AxiosResponse类型，含有config\data\headers\request\status\statusText属性
        // uni.hideLoading()
        // console.log(res)
        if (res.status == 200) {
          return res.data
        } else if (res.status == 401) {
          uni.reLaunch({
            url: '/pages/index/index',
          })
        } else {
          return Promise.reject(res.statusText)
        }
        // const { status, data } = res
        // const Data: Result = data
        // if (Data.Code === 401) {
        //   uni.reLaunch({
        //     url: '/pages/index/index',
        //   })
        //   return Promise.reject(Data.Msg)
        // } else if (Data.Code === 200) {
        //   if (Data.Msg) {
        //     uni.showToast({
        //       title: Data.Msg,
        //       icon: 'success',
        //       duration: 2000,
        //     })
        //   }

        //   return Data.Data
        // } else if (Data.Code === 5000) {
        //   const routes = getCurrentPages() //获取当前页面栈
        //   const curRoute = routes[routes.length - 1].route
        //   if (curRoute !== 'pages/index/index') {
        //     uni.reLaunch({
        //       url: '/pages/index/index',
        //     })
        //   }
        //   uni.showToast({
        //     title: Data.Msg,
        //     icon: 'error',
        //     duration: 2000,
        //   })
        // } else {
        //   uni.showToast({
        //     title: Data.Msg,
        //     icon: 'error',
        //     duration: 2000,
        //   })
        //   console.log(res.data.Msg, '失败')
        //   return Promise.reject(Data.Msg)
        // }
      },
      (err: any) => {
        uni.showToast({
          title: '网络错误，请检查您的网络或者端口！',
          icon: 'error',
          duration: 2000,
        })
        console.log('axios报错', err)
        uni.hideLoading() // 立即关闭加载框
        return Promise.reject(err)
      }
    )
  }
}
// 默认导出Request实例
export default new HttpRequest()
